package com.kpijavatraining6.module2.actionTools;

import com.kpijavatraining6.module2.questions.CheckAnswerQuestion;
import com.kpijavatraining6.module2.questions.WriteAnswerQuestion;
import com.kpijavatraining6.module2.sessionTools.AuthorisationMenu;
import com.kpijavatraining6.module2.sessionTools.History;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: Vladislav
 * Date: 30.10.13
 * Time: 15:28
 * To change this template use File | Settings | File Templates.
 */
public class Loader {

    public final String QUESTIONTYPE1 = "1";
    public final String QUESTIONTYPE2 = "2";
    private History history;
    private String userName;
    private String path;

    public Loader() {
        AuthorisationMenu authorisationMenu = new AuthorisationMenu();
        userName = authorisationMenu.getName();
        path = userName+".txt";
    }
    public Loader(String name) {
        userName = name;
        path = userName+".txt";
    }

    public History getHistory() {
        return history;
    }

    public History loadHistory() {
        File file = new File(path);
        if(!file.exists()) {
            try{
                file.createNewFile();
            } catch (IOException e) {

            }
        }
        FileInputStream fin = null;
        history = new History();
        try {
            fin = new FileInputStream(file);
            Scanner scanner = new Scanner(fin);
            StringBuffer buffer = new StringBuffer();
            while (scanner.hasNext()) {
                TestStep testStep = null;
                String line[] = scanner.nextLine().split(" ");
                if(line[0].equals(QUESTIONTYPE1)) {
                    testStep = fillTestStep1(line);
                }
                if(line[0].equals(QUESTIONTYPE2)) {
                    testStep = fillTestStep2(line);
                }
                history.push(testStep);
            }
            return history;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return history;
        }

    }
    private TestStep fillTestStep1(String[] line) {
        String question = line[1];
        String []answers = line[2].split(";");
        String rightAnswer = line[3];
        String userAnswer = line[4];
        CheckAnswerQuestion question1 = new CheckAnswerQuestion(question,rightAnswer,1, answers);
        return new TestStep(question1,userAnswer);
    }
    private TestStep fillTestStep2(String[] line) {
        String question = line[1];
        String [] rightAnswers = line[2].split(";");
        String userAnswer = line[3];
        WriteAnswerQuestion question2 = new WriteAnswerQuestion(question,1,rightAnswers);
        return new TestStep(question2,userAnswer);
    }
}

